package com.echo.boot.structure.set;

import com.echo.boot.structure.tree.binarytree.Visitor;
import com.echo.boot.structure.linearlist.linked.doublelinkedlist.MyLinkedList;
import com.echo.boot.structure.linearlist.list.MyList;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/6/2
 * Time: 18:23
 * 用 链表实现 集合
 */
public class MyLinkedSet<E> implements Set<E> {
    private MyList<E> list = new MyLinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E element) {
        return list.contains(element);
    }

    @Override
    public void add(E element) {
        int index = list.indexOf(element);
        if (index != MyList.ELEMENT_NOT_FOUND) {
            list.set(index, element);
        } else {
            list.add(element);
        }
    }

    @Override
    public void remove(E element) {
        int index = list.indexOf(element);
        if (index != MyList.ELEMENT_NOT_FOUND) {
            list.remove(index);
        }
    }

    @Override
    public void traversal(Visitor<E> visitor) {
        if (visitor == null) {
            return;
        }
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (visitor.visit(list.get(i))) {
                return;
            }
        }
    }
}
